import React, { useState } from 'react';
import { CreditCard, DollarSign, BadgeDollarSign, BadgeJapaneseYen } from 'lucide-react';
import { toast } from "sonner";
import { useTranslations } from 'next-intl';
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { post, get } from '@/lib/request';

// API响应类型定义
interface CheckoutSessionResponse {
  sessionId: string;
}

interface SessionDetailsResponse {
  data: {
    url: string;
  };
}

interface CreditsPurchaseProps {
  onPurchaseComplete?: () => void;
}

export default function CreditsPurchase({ onPurchaseComplete }: CreditsPurchaseProps) {
  const t = useTranslations('billing');
  const [currency, setCurrency] = useState<'USD' | 'CNY'>('USD');
  const [selectedAmount, setSelectedAmount] = useState<string | null>('10');
  const [customAmount, setCustomAmount] = useState<string>('');
  const [paymentDialogOpen, setPaymentDialogOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  // 如果是人民币，使用环境变量或固定汇率 1美元 = 7.3人民币
  const CNY_TO_USD_RATE = process.env.NEXT_PUBLIC_STRIPE_RATE ? parseFloat(process.env.NEXT_PUBLIC_STRIPE_RATE) : 7.3;
  const calculateCredits = (amount: string): number => {
    const numAmount = parseFloat(amount);
    if (isNaN(numAmount)) return 0;
    
    // 积分兑换比例：1美元 = 100积分
    const POINTS_CONVERSION_RATE = 100;
    
    if (currency === 'USD') {
      return Math.floor(numAmount * POINTS_CONVERSION_RATE);
    } else {
      // 使用先乘后除的方式计算积分，提高精度
      // 直接计算：人民币金额 * 积分兑换比例 / 汇率
      return Math.floor((numAmount * POINTS_CONVERSION_RATE) / CNY_TO_USD_RATE);
    }
  };

  const handleAmountSelect = (amount: string) => {
    setSelectedAmount(amount);
    setCustomAmount('');
  };

  const handleCustomAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    
    // 只允许正整数，且不能以0开头
    if (/^\d*$/.test(value)) {
      // 如果是空值，直接设置
      if (value === '') {
        setCustomAmount('');
        setSelectedAmount(null);
        return;
      }
      
      // 当输入为0或以0开头时清空输入框
      if (value === '0' || (value.length > 1 && value.startsWith('0'))) {
        setCustomAmount('');
        return;
      }
      
      // 设置金额值
      setCustomAmount(value);
      setSelectedAmount(null);
    }
  };

  // 验证购买金额是否有效
  const validatePurchaseAmount = (amount: string): { isValid: boolean; errorMessage?: string; errorDescription?: string } => {
    if (!amount || parseFloat(amount) <= 0) {
      return {
        isValid: false,
        errorMessage: t('invalidAmount'),
        errorDescription: t('pleaseSelectValidAmount')
      };
    }
    
    // 如果是人民币模式，确保金额不小于10
    if (currency === 'CNY' && parseFloat(amount) < 10) {
      return {
        isValid: false,
        errorMessage: t('insufficientAmount'),
        errorDescription: t('cnyMinimumAmount')
      };
    }

    return { isValid: true };
  };

  const handlePurchase = async () => {
    const purchaseAmount = selectedAmount || customAmount;
    const validation = validatePurchaseAmount(purchaseAmount);

    if (!validation.isValid) {
      toast.error(validation.errorMessage!, {
        description: validation.errorDescription
      });
      return;
    }

    // 在实际实现中，这里会集成 Stripe
    // 现在只是显示一个对话框来模拟支付流程
    setPaymentDialogOpen(true);
  };

  const simulatePayment = async (event: React.FormEvent) => {
    event.preventDefault();
    const purchaseAmount = selectedAmount || customAmount;
    const validation = validatePurchaseAmount(purchaseAmount);

    if (!validation.isValid) {
      toast.error(validation.errorMessage!, {
        description: validation.errorDescription
      });
      return;
    }
    setIsLoading(true);
    try {
      // 创建Stripe结账会话
      const { data, error } = await post<CheckoutSessionResponse>('/payment/create-checkout', {
        amount: parseFloat(purchaseAmount),
        currency: currency.toLowerCase() // 使用小写的货币代码，符合 z.enum(['usd', 'cny']) 的验证
      });

      if (error) {
        // 处理错误情况
        let errorMessage = t('checkoutSessionCreateFailed');
        if (typeof error === 'object' && error !== null) {
          // 使用类型断言处理可能的错误对象
          const errorObj = error as { message?: string };
          if (errorObj.message) {
            errorMessage = String(errorObj.message);
          }
        }
        throw new Error(errorMessage);
      }

      if (!data?.sessionId) {
        throw new Error(t('noDataReceived'));
      }

      // 获取会话详情
      const { data: sessionDetails, error: sessionError } = await get<SessionDetailsResponse>('/payment/session-details', {
        sessionId: data.sessionId
      });
      if (sessionError) {
        // 处理会话错误情况
        let errorMessage = t('sessionDetailsFetchFailed');
        if (typeof sessionError === 'object' && sessionError !== null) {
          // 使用类型断言处理可能的错误对象
          const errorObj = sessionError as { message?: string };
          if (errorObj.message) {
            errorMessage = String(errorObj.message);
          }
        }
        throw new Error(errorMessage);
      }

      if (!sessionDetails?.data?.url) {
        throw new Error(t('noCheckoutUrlReceived'));
      }
      setPaymentDialogOpen(false);
      // 重定向到Stripe结账页面
      window.location.href = sessionDetails.data?.url;
      
      // 如果提供了购买完成回调，则调用它
      if (onPurchaseComplete) {
        onPurchaseComplete();
      }
    } catch (err) {
      console.error('Payment error:', err);
      toast.error(t('paymentError'), {
        description: err instanceof Error ? err.message : t('unknownError')
      });
      setPaymentDialogOpen(true);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <>
      <Card className="md:col-span-2">
        <CardHeader className="flex flex-row items-center justify-between">
          <div>
            <CardTitle>{t('purchaseCredits')}</CardTitle>
            <CardDescription>{t('selectAmountDescription')}</CardDescription>
          </div>
          <div className="flex rounded-md overflow-hidden border">
            <Button 
              variant={currency === 'USD' ? "default" : "ghost"} 
              onClick={() => setCurrency('USD')} 
              className="rounded-none px-3 py-1 h-8 flex items-center gap-1"
            >
              <BadgeDollarSign className="h-4 w-4" />
              {t('currency.usd')}
            </Button>
            <Button 
              variant={currency === 'CNY' ? "default" : "ghost"} 
              onClick={() => setCurrency('CNY')} 
              className="rounded-none px-3 py-1 h-8 flex items-center gap-1"
            >
              <BadgeJapaneseYen className="h-4 w-4" />
              {t('currency.cny')}
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-3 gap-3 mb-4">
            <Button
              variant={selectedAmount === '10' ? "default" : "outline"}
              onClick={() => handleAmountSelect('10')}
              className="p-6 h-auto flex flex-col items-center"
            >
              <span className="text-lg font-semibold">{currency === 'USD' ? '$10' : '¥10'}</span>
              <span className="text-sm text-muted-foreground">
                {currency === 'USD' 
                  ? '1,000' 
                  : Math.floor((10 * 100) / CNY_TO_USD_RATE).toLocaleString()} {t('credits')}
              </span>
            </Button>
            <Button
              variant={selectedAmount === '20' ? "default" : "outline"}
              onClick={() => handleAmountSelect('20')}
              className="p-6 h-auto flex flex-col items-center"
            >
              <span className="text-lg font-semibold">{currency === 'USD' ? '$20' : '¥20'}</span>
              <span className="text-sm text-muted-foreground">
                {currency === 'USD' 
                  ? '2,000' 
                  : Math.floor((20 * 100) / CNY_TO_USD_RATE).toLocaleString()} {t('credits')}
              </span>
            </Button>
            <Button
              variant={selectedAmount === '50' ? "default" : "outline"}
              onClick={() => handleAmountSelect('50')}
              className="p-6 h-auto flex flex-col items-center"
            >
              <span className="text-lg font-semibold">{currency === 'USD' ? '$50' : '¥50'}</span>
              <span className="text-sm text-muted-foreground">
                {currency === 'USD' 
                  ? '5,000' 
                  : Math.floor((50 * 100) / CNY_TO_USD_RATE).toLocaleString()} {t('credits')}
              </span>
            </Button>
          </div>

          <div className="flex space-x-4 items-center">
            <div className="flex-1">
              <div className="flex items-center space-x-2">
                {currency === 'USD' ? <DollarSign className="h-4 w-4 text-muted-foreground" /> : <span className="h-4 w-4 text-muted-foreground flex items-center justify-center">¥</span>}
                <Input
                  type="text"
                  placeholder={t('customAmount')}
                  value={customAmount}
                  onChange={handleCustomAmountChange}
                  className="flex-1"
                />
              </div>
            </div>

            <div className="text-right">
              <div className="text-sm text-muted-foreground">{t('credits')}:</div>
              <div className="font-medium">
                {customAmount ? calculateCredits(customAmount) : selectedAmount ? calculateCredits(selectedAmount) : 0}
              </div>
            </div>
          </div>
        </CardContent>
        <CardFooter>
          <Button
            onClick={handlePurchase}
            className="w-full"
            disabled={!(selectedAmount || customAmount)}
          >
            <CreditCard className="mr-2 h-4 w-4" />
            {t('purchaseCredits')}
          </Button>
        </CardFooter>
      </Card>

      <AlertDialog open={paymentDialogOpen} onOpenChange={setPaymentDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t('completeYourPurchase')}</AlertDialogTitle>
            <AlertDialogDescription>
              {t('paymentConfirmationDescription', {
                amount: currency === 'CNY' ? `¥${selectedAmount || customAmount}` : `$${selectedAmount || customAmount}`,
                credits: customAmount ? calculateCredits(customAmount) : selectedAmount ? calculateCredits(selectedAmount) : 0
              })}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <div className="py-4">
            <div className="flex justify-between items-center mb-2">
              <span>{t('amount')}:</span>
              <span className="font-medium">{currency === 'CNY' ? '¥' : '$'}{selectedAmount || customAmount}</span>
            </div>
            <div className="flex justify-between items-center">
              <span>{t('credits')}:</span>
              <span className="font-medium">
                {customAmount ? calculateCredits(customAmount) : selectedAmount ? calculateCredits(selectedAmount) : 0}
              </span>
            </div>
          </div>
          <AlertDialogFooter>
            <AlertDialogCancel>{t('cancel')}</AlertDialogCancel>
            <AlertDialogAction onClick={simulatePayment} disabled={isLoading}>
              {isLoading ? t('processing') : t('simulatePayment')}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}
